/**
 * 服务端
 */
import express, { Request, Response, NextFunction } from "express";
import dictionary from "./routes/dictionary";
import language from "./routes/language";
import reagent from "./routes/reagent";
import user from "./routes/user";
import bottle from "./routes/bottle";
import shelf from "./routes/shelf";
import workbench from "./routes/workbench";
import designer from "./routes/designer";
import { whiteList, verifyToken, isDestroyToken } from "./utils/webtoken";

const app = express();
const port = 11921;

// 验证token
app.use((req: Request, res: Response, next: NextFunction) => {
  let isWhite = false;
  whiteList.some((item: string) => {
    if (req.url.includes(item)) {
      isWhite = true;
      return true;
    }
    return false;
  });

  if (isWhite) {
    next();
  } else {
    const token = req.headers.token as string;
    if (isDestroyToken(token)) {
      res.status(200).send({ status: 401 });
    } else {
      verifyToken(req.headers.token)
        .then((res) => {
          next();
        })
        .catch((e) => {
          res.status(401).send("invalid token");
        });
    }
  }
});

app.use(express.json({ limit: '5mb' }));
app.use(express.urlencoded({ extended: true }));

app.use("/api/dictionary", dictionary);
app.use("/api/language", language);
app.use("/api/reagent", reagent);
app.use("/api/user", user);
app.use("/api/bottle", bottle);
app.use("/api/shelf", shelf);
app.use("/api/workbench", workbench);
app.use("/api/designer", designer);

app.listen(port, () => {
  console.log(`listening at http://localhost:${port}`);
});
